package logic

import (
	"context"
	"fmt"
	"strconv"
	"usershop/api/internal/svc"
	"usershop/api/internal/types"
	"usershop/api/pkg"
	"usershop/user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginTelLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginTelLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginTelLogic {
	return &LoginTelLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginTelLogic) LoginTel(req *types.LoginTelRequest) (resp *types.ResMsg, err error) {
	// todo: 手机短信登录

	//手机号格式判断
	format := pkg.TelFormat(req.Tel)

	if format == false {
		return &types.ResMsg{
			Cre:  -2,
			Msg:  "手机号格式错误",
			Data: nil,
		}, err
	}
	//手机号登录
	_, err = l.svcCtx.UserSrv.TelLogin(l.ctx, &user.TelLoginRequest{
		Tel:    req.Tel,
		Code:   req.Code,
		Source: "login",
	})

	////查询手机号是否存在，用手机号查询用户信息
	mobile, err := l.svcCtx.UserSrv.GetUserInfoByMobile(l.ctx, &user.GetUserInfoByMobileRequest{Mobile: req.Tel})
	if err != nil {
		return nil, err
	}

	fmt.Println("gggggg9g")

	if err != nil {
		return &types.ResMsg{
			Cre:  -1,
			Msg:  "手机号登录失败",
			Data: nil,
		}, nil
	}

	if mobile.UserID == 0 {
		return &types.ResMsg{
			Cre:  -5,
			Msg:  "用户不存在",
			Data: nil,
		}, nil
	}

	token, _ := pkg.GetJwtToken(strconv.FormatInt(mobile.UserID, 10))

	return &types.ResMsg{
		Cre: 0,
		Msg: "登录成功",
		Data: map[string]interface{}{
			"token": token,
		},
	}, nil

}
